const {existClassify} = require('../service/article.service');
const {existMusic} = require('../service/music.service');
const errorTypes = require('../constants/error-types');

// 验证归档是否存在
const isExistClassify = async (ctx, next) => {
  try {
    const {classify} = ctx.request.body;
    const {id} = ctx.user;
    const result = await existClassify(classify, id);
    if (result.length !== 0) {
      const error = new Error(errorTypes.ITEM_ALREADY_EXISTS);
      ctx.app.emit('error', error, ctx);
    } else {
      await next();
    }
  } catch (error) {
    console.log(error)
  }
}

// 验证音乐是否存在
const isExistMusic = async (ctx, next) => {
  try {
    const {musicId} = ctx.request.body;
    const {id} = ctx.user;
    const result = await existMusic(musicId, id);
    if (result.length !== 0) {
      const error = new Error(errorTypes.ITEM_ALREADY_EXISTS);
      ctx.app.emit('error', error, ctx);
    } else {
      await next();
    }
  } catch (error) {
    console.log(error)
  }
}

module.exports = {
  isExistClassify,
  isExistMusic
};